<template>
    <div class="app-container">
        <!-- 搜索相关功能 -->
<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="单位" prop="unit">
                <el-input
                    v-model="queryParams.unit"
                    placeholder="请输入单位"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="岗位名称" prop="post">
                <el-input
                    v-model="queryParams.post"
                    placeholder="请输入岗位名称"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <!-- <el-form-item label="岗位类型" prop="demandType">
                <el-select v-model="queryParams.demandType" placeholder="请选择岗位类型" clearable style="width: 150px">
                    <el-option v-for="item in bus_require_type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="地市信息" prop="deptId">
  <el-select v-model="queryParams.deptId" placeholder="请选择地市" clearable filterable :filter-method="filterDept" style="width: 180px;">
    <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
  </el-select>
</el-form-item>
            
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>










        <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['bus:requireapprove:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['bus:requireapprove:edit']"
                >审批</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['bus:requireapprove:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['bus:requireapprove:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->

        <el-table v-loading="loading" :data="requireapproveList" >
            <el-table-column  width="55" align="center" />
                    <!-- <el-table-column label="序号" align="center" prop="approveId" /> -->
                    
                    <!-- <el-table-column label="审核状态" align="center" prop="approveStatus">
                        <template #default="scope">
                                <dict-tag :options="bus_requireapprove_state" :value="scope.row.approveStatus" />
                        </template>
                    </el-table-column> -->
                     <el-table-column label="单位" align="center" prop="unit" />
                    <el-table-column label="地市信息" align="center" prop="parentDeptName">
  <template #default="scope">
    <span v-if="scope.row.deptId === 100">全部地市</span>
    <span v-else>{{ scope.row.parentDeptName }}</span>
  </template>
</el-table-column>
                    <el-table-column label="岗位名称" align="center" prop="post" />
                    <!-- <el-table-column label="岗位类型" align="center" prop="demandType">
                        <template #default="scope">
                            <dict-tag :options="bus_require_type" :value="scope.row.demandType" />
                        </template>
                    </el-table-column> -->
                   
                    
                    <!-- <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bus:requireapprove:edit']">审核</el-button>
                    <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bus:requireapprove:remove']">删除</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改岗位需求审核对话框 -->
        <el-dialog :title="title" v-model="open" width="900px" append-to-body>

            <el-form ref="requireapproveRef" :model="form" :rules="rules" label-width="120px">
                <!-- 岗位需求详情字段展示，只读 -->
                <el-form-item label="岗位名称">
                    <el-input v-model="requireDetail.post" readonly />
                </el-form-item>
                <el-form-item label="课题研究目标">
  <div class="ql-editor" v-html="requireDetail.content" style="min-height: 80px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 8px; background: #fafbfc;" />
</el-form-item>
                <!-- <el-form-item label="岗位类型">
                  <el-input v-model="demandTypeLabel" readonly />
                </el-form-item> -->
                <!-- <el-input :value="bus_require_type.value.find(item => item.value === requireDetail.demandType)?.label || ''"  readonly /> -->
                
                 <!-- <el-form-item label="岗位类型">

    <el-input :value="getLabelByValue(requireDetail.demandType)"  readonly />
             </el-form-item> -->
                <el-form-item label="岗位数量">
                    <el-input v-model="requireDetail.quantity" readonly />
                </el-form-item>
                <el-form-item label="单位名称">
                    <el-input v-model="requireDetail.unit" readonly />
                </el-form-item>
                <el-form-item label="编制课题">
  <el-input v-model="requireDetail.project" readonly />
</el-form-item>
<el-form-item label="意向招收">
  <el-input v-model="requireDetail.intention" readonly />
</el-form-item>
<el-form-item label="联系人">
  <el-input v-model="requireDetail.contact" readonly />
</el-form-item>
<el-form-item label="联系方式">
  <el-input v-model="requireDetail.number" readonly />
</el-form-item>
<el-form-item label="过期时间">
  <el-input v-model="requireDetail.expirationTime" readonly />
</el-form-item>
<el-form-item v-if="requireDetail.remark" label="备注">
  <el-input v-model="requireDetail.remark" readonly />
</el-form-item>
                <!-- 审批操作字段 -->
                <el-form-item v-if="requireDetail.lastApproveReview" label="历史审核意见">
                    <div style="background: #f6f8fa; border-radius: 6px; padding: 10px 14px; color: #888; min-height: 32px; line-height: 1.6; white-space: pre-wrap;">
                        {{ requireDetail.lastApproveReview }}
                    </div>
                </el-form-item>
                <el-form-item label="审核状态" prop="approveStatus">
                    <el-radio-group v-model="form.approveStatus">
                        <el-radio v-for="dict in approveStatusOptions" :key="dict.value" :label="parseInt(dict.value)">
                            {{ dict.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="审核意见" prop="approveReview">
                    <el-input 
                      v-model="form.approveReview" 
                      type="textarea" 
                      :rows="4"
                      :maxlength="200" 
                      show-word-limit
                      placeholder="请输入审核意见" />
                </el-form-item>
                <!-- <el-form-item label="审核时间" prop="approveTime">
                    <el-date-picker clearable v-model="form.approveTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择审核时间" />
                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Requireapprove">
    import { listRequireapprove, getRequireapprove, delRequireapprove, addRequireapprove, updateRequireapprove } from "@/api/bus/requireapprove";
    import { getRequire } from "@/api/bus/require";
    import { listDept } from '@/api/system/dept';

    import { computed, onUnmounted, ref, onMounted } from 'vue';

    const { proxy } = getCurrentInstance();
    const { bus_requireapprove_state, bus_require_type } = proxy.useDict('bus_requireapprove_state', 'bus_require_type');

// 新增：只保留“通过”和“驳回”
const approveStatusOptions = computed(() =>
  bus_requireapprove_state.value
    ? bus_requireapprove_state.value
        .filter(d => d.value == 0 || d.value == 2)
        .map(d => ({
          ...d,
          label: d.label === '已通过' ? '通过' : (d.label === '被驳回' || d.label === '驳回' ? '驳回' : d.label)
        }))
    : []
);

// console.log(store.state.dict.dict['bus_require_type']);

// console.log('bus_require_type.value:', bus_require_type.value);
/* console.log(bus_require_type.value[0].label);
console.log(bus_require_type.value[0].value); */
    // bus_require_type.value.forEach(dict => {
    //     console.log(dict.label, dict.value);
    // });

//  console.log('bus_require_type.value:', bus_require_type.value);
    const requireapproveList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");

    const deptOptions = ref([]);
    onMounted(() => {
      listDept().then(res => {
        deptOptions.value = (res.data || []).filter(
          item => Number(item.parentId) === 100 && item.status === '0' && item.delFlag === '0'
        );
      });
    });

    const data = reactive({
        form: {},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            requireId: null,
            approverId: null,
            approveStatus: null,
            approveReview: null,
            approveTime: null,
            unit: null,
            post: null,
            demandType: null,
            grade: null
        },
    rules: {
        approveReview: [
            { required: true, message: "审核意见不能为空", trigger: "blur" },
            { max: 200, message: "审核意见长度不能超过200个字符", trigger: "blur" }
        ],
        approveStatus: [
            { required: true, message: "请选择审核状态", trigger: "change" }
        ]
    }
    });

    const { queryParams, form, rules } = toRefs(data);

    const requireDetail = reactive({
        post: '',
        content: '',
        demandType: '',
        demandTypeLabel: '',
        quantity: '',
        unit: '',
        project: '',
        intention: '',
        contact: '',
        number: '',
        expirationTime: '',
        remark: '',
        lastApproveReview: '' // 新增：用于存储历史审核意见
    });

    const demandTypeLabel = computed(() => {
      if ( !bus_require_type.value) return '';
      const found = bus_require_type.value.find(
        d => String(d.value) === String(requireDetail.demandType)
      );
      return found ? found.label : requireDetail.demandType;
    });
    const getLabelByValue = (value) => {
  const target = bus_require_type.value.find(item => item.value === value);
  return target ? target.label : value; // 未匹配时显示原值
}

    /** 查询岗位需求审核列表 */
    function getList() {
        loading.value = true;
        listRequireapprove(queryParams.value).then(response => {
                requireapproveList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
                approveId: null,
                requireId: null,
                approverId: null,
                approveStatus: null,
                approveReview: null,
                approveTime: null
    };
        proxy.resetForm("requireapproveRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }



    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        open.value = true;
        title.value = "添加岗位需求审核";
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _approveId = row.approveId || ids.value;
        getRequireapprove(_approveId).then(response => {
            // 历史审核意见
            requireDetail.lastApproveReview = response.data.approveReview || '';
            // 新审核输入框始终为空
            form.value = {
                ...response.data,
                approveReview: '',
                approveStatus: 0,
            };
            
            // 获取岗位需求详情
            if (response.data && response.data.requireId) {
                getRequire(response.data.requireId).then(res => {
                    Object.assign(requireDetail, res.data || {});
                    // 需求类型字典转换
                    if (requireDetail.demandType && bus_require_type.value) {
                        const found = bus_require_type.value.find(d => d.value == requireDetail.demandType);
                        requireDetail.demandTypeLabel = found ? found.label : requireDetail.demandType;
                    } else {
                        requireDetail.demandTypeLabel = requireDetail.demandType;
                    }
                });
            } else {
                Object.keys(requireDetail).forEach(k => requireDetail[k] = '');
            }
            open.value = true;
            title.value = "岗位需求审批";
        });
    }

    /** 提交按钮 */
    function submitForm() {
        // 审核意见非空校验
        if (!form.value.approveReview || !form.value.approveReview.trim()) {
            proxy.$modal.msgError("审核意见不能为空");
            return;
        }
        
        proxy.$refs["requireapproveRef"].validate(valid => {
            if (valid) {
                if (form.value.approveId != null) {
                    updateRequireapprove(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                } else {
                    addRequireapprove(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _approveIds = row.approveId || ids.value;
        proxy.$modal.confirm('是否确认删除岗位需求审核编号为"' + _approveIds + '"的数据项？').then(function() {
            return delRequireapprove(_approveIds);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    }

    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('bus/requireapprove/export', {
            ...queryParams.value
        }, `requireapprove_${new Date().getTime()}.xlsx`)
    }

    getList();
</script>